#include "mkparametersdialog.h"
#include "mkdelegates.h"
#include "mktablemodel.h"

#include "mkcore/mkcore.h"
#include "mkcore/mksettings.h"

#include <QComboBox>
#include <QLineEdit>
#include <QFormLayout>
#include <QPushButton>

#include <QDebug>

MKParametersDialog::MKParametersDialog(QWidget *parent) : QDialog(parent)
{
	init();
}

void MKParametersDialog::accept()
{
	int currentIndex = pComboBox->currentIndex();
	quint8 typeId = static_cast<quint8>(pComboBox->itemData(currentIndex, Qt::UserRole).toUInt());
	QString categoryEngName = pLECategoryEngName->text();
	QString categoryRuName = pLECategoryRuName->text();

	MKSettings *settings = MKCore::instance()->settings();
	bool isAdded = settings->addCategory(typeId, categoryRuName, categoryEngName);

	if (!isAdded)
	{
		qDebug() << "***MKParametersDialog add error";
		reject();
		return;
	}

	QDialog::accept();
	emit accepted();
}

void MKParametersDialog::reject()
{
	QDialog::reject();
	emit rejected();
}

void MKParametersDialog::init()
{
	pComboBox = new QComboBox;

	QList<QPair<quint8, QString> > typesParameters = MKCore::instance()->settings()->typesParameters();
	QListIterator<QPair<quint8, QString> > i(typesParameters);
	while(i.hasNext())
	{
		QPair<quint8, QString> typeParameters = i.next();
		pComboBox->addItem(typeParameters.second, typeParameters.first);
	}

	pLECategoryEngName = new QLineEdit;
	pLECategoryRuName = new QLineEdit;

	QVBoxLayout *pVBoxMainLayout = new QVBoxLayout(this);
	QFormLayout *pFLBaseLayout = new QFormLayout;

	pFLBaseLayout->addRow("Доход/Расход", pComboBox);
	pFLBaseLayout->addRow("Категория(кодовое название)", pLECategoryEngName);
	pFLBaseLayout->addRow("Категория(отображаемое название)", pLECategoryRuName);

	pFLBaseLayout->setFormAlignment(Qt::AlignCenter);

	QHBoxLayout *buttonLayout = new QHBoxLayout;
	QPushButton *okButton = new QPushButton("Добавить");
	QPushButton *cancelButton = new QPushButton("Отмена");

	buttonLayout->addStretch();
	buttonLayout->addWidget(okButton);
	buttonLayout->addWidget(cancelButton);
	buttonLayout->addStretch();

	connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
	connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));

	pVBoxMainLayout->addLayout(pFLBaseLayout);
	pVBoxMainLayout->addLayout(buttonLayout);
}
